﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Timers;
using HTMLConverter;
using System.Text.RegularExpressions;
using ForumsBrowser.BusinessObjects;
using ForumsBrowser.ObjectGateway;
using System.Diagnostics;
using System.Xml.Linq;
using System.Windows.Markup;

namespace ForumsBrowser
{
    /// <summary>
    /// Interaction logic for ThreadViewer.xaml
    /// </summary>
    public partial class ThreadViewer : UserControl
    {

        public ThreadViewer()
        {
            InitializeComponent();

        }
       

        public static readonly DependencyProperty IsWebBrowserProperty = DependencyProperty.Register("IsWebBrowser", typeof(bool), typeof(ThreadViewer), new PropertyMetadata(false));

        public bool IsWebBrowser
        {
            get { return (bool)this.GetValue(IsWebBrowserProperty); }
            set { this.SetValue(IsWebBrowserProperty, value); }
        }

        public void Browse(Thread thread)
        {
            this.IsWebBrowser = true;
            this.webBrowser.Navigate(new Uri(thread.Url));
        }

        public void ViewMessage(Message msg, bool newFlowDocument)
        {
            IsWebBrowser = false;

            if (msg != null)
            {
                browser.Document = FlowDocumentGenerator.Generate(msg);
                (browser.Template.FindName("PART_ContentHost", browser) as ScrollViewer).ScrollToHome();
            }
            else
            {
                MessageBox.Show("Uh-oh");
            }
        }

        public void ViewThread(Thread thread)
        {
            IsWebBrowser = false;

            this.Tag = thread.Url;

            //browser.Document = GetNewFlowDocument(thread);
            System.Threading.ThreadStart ts = () =>
                {
                    var op = browser.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            try
                            {   
                                // By the way, "Thread" in this context refers to a forums thread, not a System.Threading.Thread. 
                                // I've used Fully qualified names for System.Threading items.     
                                thread.Update(thread.IsComplete ? thread : Gateway.ThreadGet(thread.XmlUrl));
                                
                                var doc = FlowDocumentGenerator.Generate(thread); // generate the document. This works fine. 

                                browser.Document = doc; // here's where the UI stops.  The execution continues, however. 
                            }
                            catch
                            {
                                // This is called when there's just an outright problem.  This can happen when the format of the HTML snippet for a message contains
                                // some wierd settings.  
                                MessageBox.Show("Oops! I won't be able to see this thread in thread view.  I'll open it up for you in the web browser instead." +
                                    "\n\nIf you want this to be looked at, post an issue at http://forumsbrowser.codeplex.com/ and reference the following URL.\n\n" + thread.Url);
                                this.Browse(thread);
                            }
                        }
                    ),
                        System.Windows.Threading.DispatcherPriority.ContextIdle);
                    op.Completed += new EventHandler(op_Completed);
                };

            var t = new System.Threading.Thread(ts);

            t.Start();
            // (browser.Template.FindName("PART_ContentHost", browser) as ScrollViewer).ScrollToHome();

        }

        void op_Completed(object sender, EventArgs e)
        {
            (browser.Template.FindName("PART_ContentHost", browser) as ScrollViewer).ScrollToHome();
        }

        private void browser_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (!string.IsNullOrEmpty(this.Tag as string) && !this.IsWebBrowser)
            {
                this.IsWebBrowser = true;
                
              
                this.webBrowser.Navigate(new Uri(this.Tag as string));
            }
        }

        public bool WebBrowserFocused
        {
            get
            {
                var window = Window.GetWindow(webBrowser);
                Debug.WriteLine(window.ToString());
                return window.IsActive;
            }
        }

        
    }
}
